#include "dispatcher.h"
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <QDateTime>
#include "shippool.h"
#include "cargopool.h"

Dispatcher::Dispatcher(QObject *parent) : QObject(parent)
{
    m_isOnDuty = false;
    m_status = Status::IDLE;
    m_timer =new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &Dispatcher::checkApplyMessage);
}

void Dispatcher::inputApplyShipMessage(const QString ship_id)
{
    m_apply_messsage.push(ship_id);
}

std::mutex &Dispatcher::getQueMutex()
{
    return m_que_mtx;
}


std::shared_ptr<Cargo> Dispatcher::distributeCargo()
{
    return CargoPool::getInstance()->popCargo();
}

std::condition_variable &Dispatcher::getCond()
{
    return m_cond;
}


void Dispatcher::notifyOnDuty()
{

    if(m_isOnDuty){
        m_cond.notify_all();
        m_timer->start(20);
    }else{
        m_timer->stop();
    }

}

void Dispatcher::onShipTransportAway(const Ship *ship)
{
        QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
        QString message = QString("(%1) Ship ID(%2) cargo ID(%3)").arg(current_date_time).arg(ship->getId()).arg(ship->getCargoId());
        QFile file("log.txt");
        file.open(QIODevice::WriteOnly | QIODevice::Append);
        QTextStream text_stream(&file);
        text_stream << message << "\r\n";
        file.flush();
        file.close();

        m_status = Status::IDLE;

}

// 调度员每隔一小段时间从消息队里提取出船只的请求
void Dispatcher::checkApplyMessage()
{
    if(!m_apply_messsage.empty() && CargoPool::getInstance()->hasCargo() && m_status == Status::IDLE){
            std::unique_lock<std::mutex> lock(m_que_mtx);
            ShipPool::getInstance()->passShip(m_apply_messsage.front());
            m_apply_messsage.pop();
            m_status = Status::WORKING;
    }
}
